﻿#region

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Vin.Tool.AspNetCore.Singleton;
using Vin.Tool.Core.AssertCategory;

#endregion

namespace Vin.DependencyInjection.Core.Extension;

public static class ConfigurationExtension
{
    /// <summary>
    /// 初始化配置文件
    /// </summary>
    public static IConfiguration InitConfiguration(this HostApplicationBuilder service)
    {
        var configurationBuilder = new ConfigurationBuilder();

        if (!VinApp.VinInitBuilderConfig.PartialConfigDirPath.IsNullOrEmpty())
        {
            // 读取目录下的.json文件
            Directory.GetFiles(VinApp.VinInitBuilderConfig.PartialConfigDirPath!, "*.json").ToList()
                .ForEach(filePath =>
                {
                    configurationBuilder.Sources.Add(new JsonConfigurationSource()
                    {
                        Path = filePath,
                        Optional = true,
                        ReloadOnChange = true
                    });
                });
        }

        if (VinApp.VinInitBuilderConfig.PartialConfigFileNames.Count > 0)
        {
            VinApp.VinInitBuilderConfig.PartialConfigFileNames.ForEach(fileName =>
            {
                configurationBuilder.Sources.Add(new JsonConfigurationSource()
                {
                    Path = fileName,
                    Optional = true,
                    ReloadOnChange = true
                });
            });
        }

        var configuration = configurationBuilder.Build();

        VinApp.SetConfiguration(configuration);

        return configuration;
    }
}